const router = require('express').Router()
const validateToken = require('../../../../common/validateToken')
const status_code = require('../../../../common/status_code')
const db = require('../../../../db/async-db')
const { to } = require('await-to-js')
const Bee = require('../../../../common/bee/bee')

// 为用户分配角色
router.post('/user-role', async (req, resp) => {
  // 错误处理
  const handleError = (errCode, error) => {
    resp.json({
      code: errCode,
      msg: status_code[errCode],
    })
    console.error(error)
  }

  // 从请求头里取出 token
  const rawToken = req.headers.authorization
  // 验证token
  const [validateTokenError, validateTokenSuccess] = await to(
    validateToken(rawToken)
  )
  // 验证不通过处理
  if (validateTokenError || !validateTokenSuccess)
    return handleError(66013, validateTokenError)

  const { user_id, role_id } = req.body
  if (
    !Bee.StringUtils.isNumber(user_id) ||
    !Bee.StringUtils.isNotBlank(role_id)
  )
    return handleError(10003, '参数错误')

  // 将得到的参数 , 分割为数组
  // 处理多条数据
  let ridArr = role_id.split(',')
  let dataArr = [] // 要批量插入的数据
  ridArr.forEach((item) => {
    dataArr.push([user_id, parseInt(item)])
  })

  // 查询是否有该用户和角色
  const [findUsersAndRoleError, UserAndRole] = await to(
    db.query(
      'SELECT u.id user_id, r.id role_id FROM users u, role r WHERE u.id=? AND r.id IN (?)',
      [user_id, ridArr]
    )
  )
  if (
    findUsersAndRoleError ||
    !UserAndRole ||
    UserAndRole.length !== ridArr.length
  )
    return handleError(-1, findUsersAndRoleError)

  // 查询该角色是否已有该角色
  const [findUserRoleError, UserRoleList] = await to(
    db.query('SELECT * FROM user_role WHERE user_id=? AND role_id IN (?);', [
      user_id,
      ridArr,
    ])
  )
  // 如果查询有数据代表已经有该角色 不允许再分配已有的角色
  if (findUserRoleError || !UserRoleList || UserRoleList.length > 0)
    return handleError(-1, findUserRoleError)

  const [insertRoleError, insertRoleSuccess] = await to(
    db.query('INSERT INTO user_role (user_id, role_id) VALUES ?', [dataArr])
  )
  if (
    insertRoleError ||
    !insertRoleSuccess ||
    insertRoleSuccess.affectedRows === 0
  )
    return handleError(-1, insertRoleError)

  return resp.json({
    code: 0,
    msg: status_code[0],
  })
})

module.exports = router
